<?php

	/** Abstraction pour les matches
	 * @author Sebastian Mosser
	 */ 
	 
class Matche implements iPersistantData, iLookable, 
												iHTMLViewable, iXMLSerializable {


	/** Types de matches autorisé dans le système **/
	public static $MATCHE_TYPE = array ("1" => "Championnat",
																			"2" => "Tournoi",
																			"3" => "Amical",
																			"4" => "Coupe");
	public static $DIRECTION = array("-1" => "Non Approprié",
																	  "1" => "Aller",
																	  "2" => "Retour");
	
	/** Localisation des buts **/
	public static $GOAL_LOC = array("0" => "Inconnue",
																	"1" => "Surface de but",
																	"2" => "Surface de réparation",
																	"3" => "En dehors de la surface");
	
	/** Type des buts **/
	public static $GOAL_TYPE = array("0" => "Inconnu",
																	 "1" => "Action de Jeu",
																	 "2" => "Corner",
																	 "3" => "Coup Franc",
																	 "4" => "Contre son camp",
																	 "5" => "Penalty");

	public static $EXISTANT_MARK = array( "-1" => "Non noté",
																				 "0" => "0",
																				 "1" => "1",
																				 "2" => "2",
																				 "3" => "3",
																				 "4" => "4",
																				 "5" => "5",
																				 "6" => "6",
																				 "7" => "7",
																				 "8" => "8",
																				 "9" => "9",
																				"10" => "10");
																				
	public static $ROLES = array("-1" => "Inconnu",
															  "1" => "Gardien", 
															  "2" => "Défenseur",
															  "3" => "Milieu Défensif",
															  "4" => "Milieu Offensif",
															  "5" => "Attaquant",
															  "6" => "Remplaçant");

	public static $GROUND_TYPE = array("-1" => "Non Spécifié",
																		 "1"  => "Pelouse Normale",
																 		 "2"  => "Pelouse Bosselée",
																 		 "3"  => "Pelouse Détrempée",
																 		 "4"  => "Synthétique",
																		 "5"  => "Synthétique NG",
																		 "6"  => "Terre",
																		 "7"  => "Hockey (PSCE 9)");
																		 
	public static $GROUND = array("-1" => "Non Spécifié",
																"1" => "Domicile",
																"2" => "Exterieur",
																"3" => "Neutre");

	public static $FOR_US   = "0";
	public static $FOR_THEM = "1";

	private $_id;     ///< identifiant unique du matche
	
	private $_matchNo;    ///< numéro du matche
	private $_matchWebNo; ///< Numéro du matche pour le minitel Fédé

	private $_goalsUs;    ///< Nombres de buts marqués par NOTRE équipe
	private $_goalsThem;  ///< Nombres de buts marqué par les autres
	private $_opponent;   ///< Nom de l'équipe adverse
	private $_direction;  ///< Sens du matche (aller / retour)

	private $_length;     ///< durée du matche
	private $_date;       ///< Date du matche (instance de date)
	private $_day;        ///< journée du matche (1,2, ...)
	private $_type;       ///< type de matche (tournoi, amical, championnat, ...)
	private $_ground;     ///< terrain (a dmomicile, ...)
	private $_groundType; ///< type de terrain
	
	private $_internalComment; ///< commentaire Interne
	private $_externalComment; ///< commentaire interne

	private $_players;  ///< Tableau des joueurs du matche
	private $_goals;    ///< Tableau des buts du matche
	private $_warnings; ///< Tableau des cartons du matche

	private $_pictures; ///< Tableau des photos du matche (5 max)
	private $_movie;    ///< Vidéo du matche
	
	private $PIC_PATH;
	private $PIC_URL;
	private $MOVIE_PATH;
	private $MOVIE_URL;
	
	public function __construct($id = -1) {
		$this->_id       = $id;
		$this->_players  = array();
		$this->_goals    = array();
		$this->_warnings = array();
		$this->_pictures = array();
		for ($i = 1; $i < 6; $i++)
			$this->_pictures[$i] = "";
		$this->PIC_PATH = BALLOON_FS_PATH . "data/img/matches/";
		$this->PIC_URL = BALLOON_BASE_URL . "data/img/matches/";
		$this->MOVIE_PATH = BALLOON_FS_PATH . "data/videos/matches/";
		$this->MOVIE_URL = BALLOON_BASE_URL . "data/videos/matches/";
	}
	
	public function xmlExport($e, $type="") {
		
		$idM = htmlentities($this->_id,ENT_COMPAT,"UTF-8");
		$type = htmlentities(self::$MATCHE_TYPE[$this->_type],ENT_COMPAT,"UTF-8");
		$direction = htmlentities(self::$DIRECTION[$this->_direction],
															ENT_COMPAT,"UTF-8");
		$day       = htmlentities($this->_day,ENT_COMPAT,"UTF-8");
		$us        = $this->getTeamId();
		$scoreUs   = htmlentities($this->_goalsUs,ENT_COMPAT,"UTF-8");
		$them      = htmlentities($this->_opponent,ENT_COMPAT,"UTF-8"); 
		$scoreThem = htmlentities($this->_goalsThem,ENT_COMPAT,"UTF-8");
		$comment   = htmlentities($this->_externalComment,ENT_COMPAT,"UTF-8");
		$date = htmlentities(Date::fromSql($this->_date)->prettyPrint(),
													ENT_COMPAT,"UTF-8");
		$rawdate = $this->_date;
		$ground = $this->_ground;
		
		$goals = "		<goals />";
		$content = "";
		foreach($this->_goals as $k => $v) {
			if ($v["forUs"] != self::$FOR_US)
				continue;
			$minute = $v["minute"];
			$goaler = $v["player"];
			$e->visitMember($goaler,"player");
			$helper = $v["helper"];
			$e->visitMember($helper,"player");
			$content .= <<<EOS

			<goal>
				<minute>${minute}</minute>
				<goaler>${goaler}</goaler>
				<helper>${helper}</helper>
			</goal>
EOS;
		}
		if ($content != "")
			$goals = "		<goals>$content\n		</goals>";
		
		$players = "		<players />";
		$content = "";
		foreach($this->_players as $k => $v) {
			$id = $k;
			$e->visitMember($k,"player");
			$role = htmlentities(self::$ROLES[$v["role"]],ENT_COMPAT,"UTF-8");
			$content .= <<<EOS

			<player>
				<id>${id}</id>
				<role>${role}</role>
			</player>
EOS;
		}
		if ($content != "")
			$players = "		<players>${content}\n		</players>";
		
		$pictures = "			<pictures />";
		$content = "";
		$i = 0;
		
		for ($i = 1; $i < 6; $i++) {
			if ($this->_pictures[$i] == "")
				continue;
			$pics = $this->computePicsFileName($i,$this->_pictures[$i]);
			$e->insertPicture($pics["large"],$pics["small"]);
			$content .= <<<EOS
<picture>${pics["large"]}</picture>
EOS;
		}
		if ($content != "")
			$pictures = "		<pictures> $content </pictures>";
		
		$movie = "";
		$ans = <<<EOS
	<matche id="${idM}">
		<type>${type}</type>
		<ground>${ground}</ground>
		<direction>${direction}</direction>
		<day>${day}</day>
		<date>${rawdate}</date>
		<pretty_date>${date}</pretty_date>
		<us>${us}</us>
		<score_us>${scoreUs}</score_us>
		<them>${them}</them>
		<score_them>${scoreThem}</score_them>
		<comment>${comment}</comment>
${players}
${goals}
${pictures}
		<movie>${movie}</movie>
	</matche>
EOS;
		
		$e->insertData("matche",$this->_id,$ans);
	}
	
	
	/** Accesseur en lecture **/
	public function getPlayers()     { return $this->_players;    }
	public function getWarnings()    { return $this->_warnings;   }
	public function getGoals()       { return $this->_goals;      }
	
	public function getMatcheNo()    { return $this->_matchNo;   }
	public function getMatcheWebNo() { return $this->_matchWebNo; }
	public function getDate()        { return $this->_date;       }
	public function getDay()         { return $this->_day;        }
	public function getLength()      { return $this->_length;     }
	public function getOpponent()    { return $this->_opponent;   }
	public function getDirection()   { return $this->_direction;  }
	public function getType()        { return $this->_type;       }
	public function getGoalsUs()     { return $this->_goalsUs;    }
	public function getGoalsThem()   { return $this->_goalsThem;  }
	
	public function getGround()      { return $this->_ground;     }
	public function getGroundType()  { return $this->_groundType; }
	
	public function getInternalComment() { return $this->_internalComment; }
	public function getExternalComment() { return $this->_externalComment; }
	
	public function getMovieUrl() {
		if ($this->_movie == '')
			return False;
		if (! file_exists($this->MOVIE_PATH . $this->_movie))
			return False;
		return $this->MOVIE_URL . $this->_movie;
	}
	
	/** Accesseurs en écriture **/
	public function setMatchNo($m)         { $this->_matchNo = $m;         }
	public function setMatchWebNo($m)      { $this->_matchWebNo = $m;      }
	
	public function setGoalsUs($n)         { $this->_goalsUs = $n;         }
	public function setGoalsThem($n)       { $this->_goalsThem = $n;      }
	public function setOpponent($n)        { $this->_opponent = $n;        }
	public function setDirection($d)       { $this->_direction = $d;       }
	
	public function setLength($l)          { $this->_length = $l;          }
	public function setDate($d)            { $this->_date = $d;            }
	public function setDay($d)             { $this->_day = $d;             }
	public function setType($type)         { $this->_type = $type;         }
	
	public function setGround($g)          { $this->_ground = $g;          }
	public function setGroundType($gt)     { $this->_groundType = $gt;     }
	
	public function setInternalComment($i) { $this->_internalComment = $i; }
	public function setExternalcomment($e) { $this->_externalComment = $e; }

	public function setMovie($fileName)    {	$this->_movie = $fileName;   }

	public function addPlayer($p, $role, $mark, $gameTime) {
		$tmp = array();
		$tmp["role"]     = $role;
		$tmp["mark"]     = $mark;
		$tmp["gameTime"] = $gameTime;
		$this->_players[$p] = $tmp;
	}
	
	public function delPlayer($p) {
		if (array_key_exists($p,$this->_players))
			unset($this->_players[$p]);
	}

	public function addGoal($p, $h, $t, $m, $c, $l, $f,$id = -1) {
		$content = array();
		$content["player"]  = $p; $content["helper"]       = $h;
		$content["type"]    = $t; $content["minute"]       = $m;
		$content["comment"] = $c; $content["localisation"] = $l;
		$content["forUs"]   = $f;
		$this->_goals[$id] = $content; 
	}
	
	public function delGoal($id) {
		if (array_key_exists($id,$this->_goals))
			unset($this->_goals[$id]);
	}

	public function addWarning($player, $type, $minute, $comment, $id = -1) {
		$content = array();
		$content["player"] = $player; $content["type"]    = $type;
		$content["minute"] = $minute; $content["comment"] = $comment;
		$this->_warnings[$id] = $content;
	}
	
	public function delWarning($id) {
		if (array_key_exists($id, $this->_warnings))
			unset($this->_warnings[$id]);
	}
	
	public function addPicture($id,$fileName) {
		$this->_pictures[$id] = $fileName;
	}
	
	public function delPicture($id) {
		if (array_key_exists($id,$this->_pictures))
		unset($this->_pictures[$id]);
	}
	
	
	
	private function computePicsFileName($id,$ext) {
		$ans = array();
		$prefix = $this->PIC_PATH.$this->_id."-" . $id;
		$ans["small"] = $prefix . "-SMALL".$ext;
		$ans["large"] = $prefix . "-LARGE".$ext;
		return $ans;
	}
	
	private function computePicsUrl($id,$ext) {
		$ans = array();
		$prefix = $this->PIC_URL.$this->_id."-" . $id;
		$ans["small"] = $prefix . "-SMALL".$ext;
		$ans["large"] = $prefix . "-LARGE".$ext;
		return $ans;
	}
	
	public function loadPicture($id,$file) {
		$tmpPic = new Picture($file);
		$ext = $tmpPic->getExtension();
		if (! $ext)
			return False; // Type de fichier non géré
		$names = $this->computePicsFileName($id,$ext);
		$small = $tmpPic->duplicate($names["small"]);
		$large = $tmpPic->duplicate($names["large"]);
		$tmpPic->delete();
		
		$small->resize(133,100);
		$large->resize(1024,768);
		$large->tag(Picture::$TAG_VALUE);
		$this->addPicture($id,$ext);
		return True;
	}
	
	public function unloadPicture($id) {
		$ext = $this->_pictures[$id];
		$names = $this->computePicsFileName($id,$ext);
		if (file_exists($names["small"]))
			unlink($names["small"]);
		if (file_exists($names["large"]))
			unlink($names["large"]);
		$this->addPicture($id,'');
	}
	
	public function getPicture($id,$text = True) {
		if ($this->_pictures[$id] == '') {
			if ($text)
				return "<em> Pas d'image ... </em>";
			else
				return "";
		}
		else {
			$tmp = $this->computePicsUrl($id,$this->_pictures[$id]);
			$large = $tmp["large"]; $small = $tmp["small"];
			$ans = <<<EOS
<a href="${large}" target="_blank"> 
	<img src="${small}" alt="Photo ${id}" /> 
</a> 
EOS;
			if ($text) {
				$ans .= <<<EOS
<br />
<p> 
	Cliquez sur l'image pour voir la version <strong>haute définition</strong>.
</p>
EOS;
			}
			return $ans;
		}
	}
	
	public function loadMovie($uploadedFile) {
		$name = str_replace(" ","_",$uploadedFile->getOriginalName());
		if (file_exists($this->MOVIE_PATH.$name))
			return False;
		
		$uploadedFile->moveToDest($this->MOVIE_PATH.$name);
		$this->_movie = $name;
		return True;
	}
	
	public function unloadMovie() {
		$name = $this->_movie;
		if ($name == "")
			return;
		if (file_exists($this->MOVIE_PATH.$name))
			unlink($this->MOVIE_PATH.$name);
		$this->_movie = "";
	}

	/** Implémentation de la persistance des données **/
	public static function createTable() {
		$myDb = Database::getSingleton();
	
		/** Relation principale **/
		$sql  = <<<EOS
CREATE TABLE IF NOT EXISTS `matche` (
	`id`               INTEGER NOT NULL PRIMARY KEY auto_increment,
	`matche_no`        VARCHAR(10)  NOT NULL,
	`web_no`           VARCHAR(10)  NOT NULL,
	`goal_us`          INTEGER      NOT NULL,
	`goals_them`       INTEGER      NOT NULL,
	`oponnent`         VARCHAR(50)  NOT NULL,
	`direction`        INTEGER      NOT NULL,
	`length`           INTEGER      NOT NULL,
	`date`             VARCHAR(10)  NOT NULL,
	`day`              INTEGER      NOT NULL,
	`type`             INTEGER      NOT NULL,
	`internal_comment` LONGTEXT     NOT NULL,
	`external_comment` LONGTEXT     NOT NULL,
	`picture_1`        VARCHAR(255) NOT NULL,
	`picture_2`        VARCHAR(255) NOT NULL,
	`picture_3`        VARCHAR(255) NOT NULL,
	`picture_4`        VARCHAR(255) NOT NULL,
	`picture_5`        VARCHAR(255) NOT NULL,
	`movie`            VARCHAR(255) NOT NULL,
	`ground`           INTEGER      NOT NULL,
	`ground_type`      INTEGER      NOT NULL);
EOS;
		$myDb->execute($sql);

		/** Relation de liaisons avec les joueurs **/
		$sql = <<<EOS
CREATE TABLE IF NOT EXISTS `matche_member_lnk` (
	`id` INTEGER NOT NULL PRIMARY KEY auto_increment,
	`matche_id` INTEGER NOT NULL,
	`member_id` INTEGER NOT NULL,
	`role`      INTEGER NOT NULL,
	`mark`      INTEGER NOT NULL,
	`game_time` INTEGER NOT NULL);
EOS;
		$myDb->execute($sql);
	
		/** Relation de liaison avec les buts **/
		$sql = <<<EOS
CREATE TABLE IF NOT EXISTS `matche_goal_lnk` (
	`id`           INTEGER  NOT NULL PRIMARY KEY auto_increment,
	`matche_id`    INTEGER  NOT NULL,
	`member_id`    INTEGER  NOT NULL,
	`helper_id`    INTEGER  NOT NULL,
	`type`         INTEGER  NOT NULL,
	`minute`       INTEGER  NOT NULL,
	`comment`      LONGTEXT NOT NULL,
	`for_us`       INTEGER  NOT NULL,
	`localisation` INTEGER  NOT NULL);
EOS;
		$myDb->execute($sql);
	
		/** Relation de liaisons avec les cartons **/
		$sql = <<<EOS
CREATE TABLE IF NOT EXISTS `matche_warning_lnk` (
	`id` INTEGER NOT NULL PRIMARY KEY auto_increment,
	`matche_id`  INTEGER NOT NULL,
	`member_id`  INTEGER NOT NULL,
	`type`       INTEGER NOT NULL,
	`minute`     INTEGER NOT NULL,
	`comment`    LONGTEXT NOT NULL);
EOS;
		$myDb->execute($sql);
	}
	
	public static function dropTable() {
		$myDb = Database::getSingleton();
		$myDb->execute("DROP TABLE IF EXISTS `matche`; ");
		$myDb->execute("DROP TABLE IF EXISTS `matche_member_lnk`; ");
		$myDb->execute("DROP TABLE IF EXISTS `matche_goal_lnk`; ");
		$myDb->execute("DROP TABLE IF EXISTS `matche_warning_lnk`; ");
	}
	
	private function manageLnk() {
		$this->managePlayersLnk();
		$this->manageGoalsLnk();
		$this->manageWarningLnk();
	}
	
	private function managePlayersLnk() {
		// Récupération de la base de données
	  $myDb = Database::getSingleton();
	  $id = $this->_id;
	  
	  // Récupération des infos présentes sur les fonctions :
	  $sql = "SELECT * FROM `matche_member_lnk` WHERE `matche_id` = $id";
	  $ans = $myDb->execute($sql);
	  
	  $tmp = $this->_players;
	  
	  while (($row = Database::assoc($ans)) != False) {
	    if (array_key_exists($row["member_id"],$tmp)) {
	      // \exists quelque chose dans la base ...
	      $volatile   = $tmp[$row["member_id"]];
	      $persistant             = array();
	      $persistant["role"]     = $row["role"];
	      $persistant["mark"]     = $row["mark"];
	      $persistant["gameTime"] = $row["game_time"];
	      
	      if ( $volatile != $persistant ) {
	      	// Les données ont changée ... database update
	      	$r = Database::escape($volatile["role"]);
	      	$m = Database::escape($volatile["mark"]);
	      	$g = Database::escape($volatile["gameTime"]);
	      	$query  = "UPDATE `matche_member_lnk` SET \n";
	      	$query .= "  `role`      = '$r', ";
	      	$query .= "  `mark`      = '$m', ";
	      	$query .= "  `game_time` = '$g' ";
	      	$query .= "  WHERE `id` = " . $row["id"];
	      	$myDb->execute($query);
	      } 
	     
	      // Quoi qu'il arrive, on dégage du tableau temporaire
	      unset($tmp[$row["member_id"]]);
	    }
	    else {
	    	// On n'est plus dans les données volatiles
	    	$query = 
	    		 "DELETE FROM `matche_member_lnk` WHERE `id` = " . $row["id"];
	    	$myDb->execute($query);
	    }
	  } // fin du while sur le flux du DBMS
	  
	  // A ce stade, le tableau temporaire contient uniquement les tuple a ajouter
	  $id = Database::escape($this->_id);
	  foreach($tmp as $k => $v) {
	  	$key = Database::escape($k);
	  	$r   = Database::escape($v["role"]);
	  	$m   = Database::escape($v["mark"]);
	  	$g   = Database::escape($v["gameTime"]);
	  	$sql  = "INSERT INTO `matche_member_lnk` VALUES ('', ";
	  	$sql .= "  '$id', '$key', '$r','$m','$g');";
	  	$myDb->execute($sql);
	  }
	  // synchronisation finie !
	}
	
	private function manageGoalsLnk() {
		// Récupération de la base de données
	  $myDb = Database::getSingleton();
	  $id = $this->_id;
	  
	  // Récupération des infos présentes sur les fonctions :
	  $sql = "SELECT * FROM `matche_goal_lnk` WHERE `matche_id` = $id";
	  $ans = $myDb->execute($sql);
	  
	  $tmp = $this->_goals;
	  
	  while (($row = Database::assoc($ans)) != False) {
	    if (array_key_exists($row["id"],$tmp)) {
	      // \exists quelque chose dans la base ...
	      $volatile   = $tmp[$row["id"]];
	      $persistant                 = array();
	      $persistant["player"]       = $row["member_id"];
	      $persistant["helper"]       = $row["helper_id"];
	      $persistant["type"]         = $row["type"];
	      $persistant["minute"]       = $row["minute"];
	      $persistant["comment"]      = $row["comment"];
	      $persistant["localisation"] = $row["localisation"];
	      $persistant["forUs"]        = $row["for_us"];
	      
	      if ( $volatile != $persistant ) {
	      	// Les données ont changée ... database update
	      	$p = Database::escape($volatile["player"]);
	      	$h = Database::escape($volatile["helper"]);
	      	$t = Database::escape($volatile["type"]);
	     	 	$m = Database::escape($volatile["minute"]);
					$c = Database::escape($volatile["comment"]);
	      	$l = Database::escape($volatile["localisation"]);
	      	$f = Database::escape($volatile["forUs"]);
	      	
	      	$query  = "UPDATE `matche_goal_lnk` SET \n";
	      	$query .= "  `member_id`    = '$p', ";
	      	$query .= "  `helper_id`    = '$h', ";
	      	$query .= "  `type`         = '$t', ";
	      	$query .= "  `minute`       = '$m', ";
	      	$query .= "  `comment`      = '$c', ";
	      	$query .= "  `for_us`       = '$f', ";
	      	$query .= "  `localisation` = '$l' ";
	      	$query .= "  WHERE `id` = " . $row["id"];
	      	$myDb->execute($query);
	      } 
	     
	      // Quoi qu'il arrive, on dégage du tableau temporaire
	      unset($tmp[$row["id"]]);
	    }
	    else {
	    	// On n'est plus dans les données volatiles
	    	$query = 
	    		 "DELETE FROM `matche_goal_lnk` WHERE `id` = " . $row["id"];
	    	$myDb->execute($query);
	    }
	  } // fin du while sur le flux du DBMS
	  
	  // A ce stade, le tableau temporaire contient uniquement les tuple a ajouter
	  $id = Database::escape($this->_id);
	  foreach($tmp as $k => $v) {
	  	$key = Database::escape($k);
	  	$p = Database::escape($v["player"]);
	    $h = Database::escape($v["helper"]);
	    $t = Database::escape($v["type"]);
	    $m = Database::escape($v["minute"]);
			$c = Database::escape($v["comment"]);
	    $l = Database::escape($v["localisation"]);
	    $f = Database::escape($v["forUs"]);
	  	
	  	$sql  = "INSERT INTO `matche_goal_lnk` VALUES ('', ";
	  	$sql .= "  '$id', '$p', '$h','$t','$m', '$c', '$f', '$l');";
	  	$myDb->execute($sql);
	  }
	  // synchronisation finie !
	}
	
	private function manageWarningLnk() {
		// Récupération de la base de données
	  $myDb = Database::getSingleton();
	  $id = $this->_id;
	  
	  // Récupération des infos présentes sur les fonctions :
	  $sql = "SELECT * FROM `matche_warning_lnk` WHERE `matche_id` = $id";
	  $ans = $myDb->execute($sql);
	  
	  $tmp = $this->_warnings;
	  
	  while (($row = Database::assoc($ans)) != False) {
	    if (array_key_exists($row["id"],$tmp)) {
	      // \exists quelque chose dans la base ...
	      $volatile   = $tmp[$row["id"]];
	      $persistant            = array();
	      $persistant["player"]  = $row["member_id"];
	      $persistant["type"]    = $row["type"];
	      $persistant["minute"]  = $row["minute"];
	      $persistant["comment"] = $row["comment"];
	      
	      if ( $volatile != $persistant ) {
	      	// Les données ont changée ... database update
	      	$p = Database::escape($volatile["player"]);
	      	$t = Database::escape($volatile["type"]);
	     	 	$m = Database::escape($volatile["minute"]);
					$c = Database::escape($volatile["comment"]);
	      	
	      	$query  = "UPDATE `matche_warning_lnk` SET \n";
	      	$query .= "  `member_id`    = '$p', ";
	      	$query .= "  `type`         = '$t', ";
	      	$query .= "  `minute`       = '$m', ";
	      	$query .= "  `comment`      = '$c', ";
	      	$query .= "  WHERE `id` = " . $row["id"];
	      	$myDb->execute($query);
	      } 
	     
	      // Quoi qu'il arrive, on dégage du tableau temporaire
	      unset($tmp[$row["id"]]);
	    }
	    else {
	    	// On n'est plus dans les données volatiles
	    	$query = 
	    		 "DELETE FROM `matche_warning_lnk` WHERE `id` = " . $row["id"];
	    	$myDb->execute($query);
	    }
	  } // fin du while sur le flux du DBMS
	  
	  // A ce stade, le tableau temporaire contient uniquement les tuple a ajouter
	  $id = Database::escape($this->_id);
	  foreach($tmp as $k => $v) {
	  	$key = Database::escape($k);
	  	$p = Database::escape($v["player"]);
	    $t = Database::escape($v["type"]);
	    $m = Database::escape($v["minute"]);
			$c = Database::escape($v["comment"]);
	  	
	  	$sql  = "INSERT INTO `matche_warning_lnk` VALUES ('', ";
	  	$sql .= "  '$id', '$p','$t','$m','$c');";
	  	$myDb->execute($sql);
	  }
	  // synchronisation finie !
	}
	
	public function create() {
		if ($this->_id != -1)
			throw new Exception("Still Existing !!",1);
		
		//var_dump($this);
		//exit(1);
		
		// Récupération des données
		$matchNo         = Database::escape($this->_matchNo);
		$matchWebNo      = Database::escape($this->_matchWebNo);
		$goalsUs         = Database::escape($this->_goalsUs);
		$goalsThem       = Database::escape($this->_goalsThem);
		$opponent        = Database::escape($this->_opponent);
		$direction       = Database::escape($this->_direction);
		$length          = Database::escape($this->_length);
		$date            = Database::escape($this->_date);
		$day             = Database::escape($this->_day);
		$type            = Database::escape($this->_type);
		$internalComment = Database::escape($this->_internalComment);
		$externalComment = Database::escape($this->_externalComment);
		$picture1        = Database::escape($this->_pictures[1]);
		$picture2        = Database::escape($this->_pictures[2]);
		$picture3        = Database::escape($this->_pictures[3]);
		$picture4        = Database::escape($this->_pictures[4]);
		$picture5        = Database::escape($this->_pictures[5]);
		$movie           = Database::escape($this->_movie);
		$ground          = Database::escape($this->_ground);
		$groundType      = Database::escape($this->_groundType);
		
		/** Création de la requete de base de données **/
		$sql = <<<EOS
INSERT INTO `matche` VALUES ('', '$matchNo', '$matchWebNo', '$goalsUs', 
														 '$goalsThem', '$opponent', '$direction', '$length',
														 '$date', '$day', '$type', '$internalComment', 
														 '$externalComment','$picture1', '$picture2', 
														 '$picture3', '$picture4', '$picture5', '$movie',
														 '$ground', '$groundType');
EOS;
		$myDb = Database::getSingleton();
		$ans = $myDb->executeInsert($sql);
		$this->_id = $ans[0];
		$this->manageLnk();
		return $ans[0];
	}
	
	public static function read($id) {
		$id = Database::escape($id);
		if ($id == -1)
			throw new Exception("Doesn't exist !!",1);
			
		// Récupération en base de données
		$sql = "SELECT * FROM `matche` WHERE `id` = $id";
		$myDb = Database::getSingleton();
		$ans = Database::assoc($myDb->execute($sql));
		
		if (! $ans)
			throw new Exception("$id does'nt exists !!",1);
		
		/** Instanciation de la relation principale **/
		$aMatche = new Matche($id);
		$aMatche->setMatchNo($ans["matche_no"]);
		$aMatche->setMatchWebNo($ans["web_no"]);
		$aMatche->setGoalsUs($ans["goal_us"]);
		$aMatche->setGoalsThem($ans["goals_them"]);
		$aMatche->setOpponent($ans["oponnent"]);
		$aMatche->setDirection($ans["direction"]);
		$aMatche->setLength($ans["length"]);
		$aMatche->setDate($ans["date"]);
		$aMatche->setDay($ans["day"]);
		$aMatche->setType($ans["type"]);
		$aMatche->setInternalComment($ans["internal_comment"]);
		$aMatche->setExternalComment($ans["external_comment"]);
		$aMatche->addPicture(1,$ans["picture_1"]);
		$aMatche->addPicture(2,$ans["picture_2"]);
		$aMatche->addPicture(3,$ans["picture_3"]);
		$aMatche->addPicture(4,$ans["picture_4"]);
		$aMatche->addPicture(5,$ans["picture_5"]);
		$aMatche->setMovie($ans["movie"]);
		$aMatche->setGround($ans["ground"]);
		$aMatche->setGroundType($ans["ground_type"]);
		
		/** Chargement des liaisons **/
		
		// Liaisons avec les joueurs :
		$sql = "SELECT * FROM `matche_member_lnk` WHERE `matche_id` = $id";
		$ans = $myDb->execute($sql);
		while (($row = Database::assoc($ans)) != False)
			$aMatche->addPlayer($row["member_id"],$row["role"],$row["mark"],
													$row["game_time"]);
		// Liaison avec les buts : 
		$sql = "SELECT * FROM `matche_goal_lnk` WHERE `matche_id` = $id";
		$ans = $myDb->execute($sql);
		while (($row = Database::assoc($ans)) != False)
			$aMatche->addGoal($row["member_id"],$row["helper_id"],$row["type"],
												$row["minute"],$row["comment"],$row["localisation"],
												$row["for_us"], $row["id"]);
		// Liaisons avec les cartons
		$sql = "SELECT * FROM `matche_warning_lnk` WHERE `matche_id` = $id";
		$ans = $myDb->execute($sql);
		while (($row = Database::assoc($ans)) != False)
			$aMatche->addWarning($row["member_id"],$row["type"],$row["minute"],
													 $row["comment"], $row["id"]);
		
		/** Renvoi du résultat **/
		return $aMatche;
	}
	
	public function update() { 
		if ($this->_id == -1)
			throw new Exception("Doesn't exists !!",1);
		// Récupération des données
		$id              = Database::escape($this->_id);
		$matchNo         = Database::escape($this->_matchNo);
		$matchWebNo      = Database::escape($this->_matchWebNo);
		$goalsUs         = Database::escape($this->_goalsUs);
		$goalsThem       = Database::escape($this->_goalsThem);
		$opponent        = Database::escape($this->_opponent);
		$direction       = Database::escape($this->_direction);
		$length          = Database::escape($this->_length);
		$date            = Database::escape($this->_date);
		$day             = Database::escape($this->_day);
		$type            = Database::escape($this->_type);
		$internalComment = Database::escape($this->_internalComment);
		$externalComment = Database::escape($this->_externalComment);
		$picture1        = Database::escape($this->_pictures[1]);
		$picture2        = Database::escape($this->_pictures[2]);
		$picture3        = Database::escape($this->_pictures[3]);
		$picture4        = Database::escape($this->_pictures[4]);
		$picture5        = Database::escape($this->_pictures[5]);
		$movie           = Database::escape($this->_movie);
		$ground          = Database::escape($this->_ground);
		$groundType      = Database::escape($this->_groundType);
	
		// Création de la requete
		$sql = <<<EOS
UPDATE `matche` SET 
  `matche_no` = '$matchNo',
  `web_no`    = '$matchWebNo',
  `goal_us`   =  '$goalsUs',
  `goals_them` = '$goalsThem',
  `oponnent`   = '$opponent',
  `direction`  = '$direction',
  `length`     = '$length',
  `date`       = '$date',
  `day`        = '$day',
  `type`       = '$type',
  `internal_comment` = '$internalComment',
  `external_comment` = '$externalComment',
  `picture_1`        = '$picture1',
  `picture_2`        = '$picture2',
  `picture_3`        = '$picture3',
  `picture_4`        = '$picture4',
  `picture_5`        = '$picture5',
  `movie`            = '$movie',
  `ground`           = '$ground',
  `ground_type`      = '$groundType'
WHERE `id` = $id;  
EOS;
		$myDb = Database::getSingleton();
		$myDb->execute($sql);
		
		// Mise a jour des liaisons
		$this->manageLnk();
	}
	
	public function delete() { 
		$id = Database::escape($this->_id);
		$myDb = Database::getSingleton();
		
		// On dégage l'entrée dans la relation principale : 
		$myDb->execute("DELETE FROM `matche` WHERE `id` = $id; ");
		// Et idem dans les relations annexes
		$myDb->execute("DELETE FROM `matche_member_lnk` WHERE `matche_id` = $id;");
		$myDb->execute("DELETE FROM `matche_goal_lnk` WHERE `matche_id` = $id;");
		$myDb->execute("DELETE FROM `matche_warning_lnk` WHERE `matche_id` = $id");
	}
	
		public function tag() {
		$tmp = array();
		$tmp[0] = "Matche";
		$tmp[1] = $this->_id;
		return $tmp;
	}
	
	public function soundsLike($o) {
		return $this->_opponent == $o->_opponent && $this->_goalsUs == $o->_goalsUs; 
	}
	
	public function getTeamName() {
		$id = $this->getTeamId();
		$aTeam = Team::read($id);
		return $aTeam->displayShort();
	}
	
	public function getTeamId() {
		$id = Database::escape($this->_id);
		$sql = "SELECT `team_id` from `team_matche_lnk` WHERE `matche_id` = $id;";
		$myDb = Database::getSingleton();
		$ans = Database::assoc($myDb->execute($sql));
		return $ans["team_id"];
	}
	
	/** Interface de recherche **/
	
	// Le filtre est l'équipe 
	public static function lookFor($filter) {
		$filter = Database::escape($filter);
		$sql =<<<EOS
SELECT 
  team_matche_lnk.matche_id AS matche_id, matche.date AS date 
FROM 
  team_matche_lnk, matche 
WHERE 
  matche.id = team_matche_lnk.matche_id 
AND 
  team_matche_lnk.team_id = $filter 
ORDER BY 
  matche.date DESC;
EOS;

		$myDb = Database::getSingleton();
		$ans = $myDb->execute($sql);
		if (! $ans)
			return False;
		return $ans;
	}
	
	public static function showResult($resultSet, $scriptUrl = "") {
	
		$content = "";
		while (($row = Database::assoc($resultSet)) != False) {
			$aMatche = Matche::read($row["matche_id"]);
			$content .= "<tr> " . $aMatche->displayInline($scriptUrl) . "</tr>";
		}
		
		if ($content == "") {
			$ans = "<div align=\"center\"> <span class=\"error\">";
			$ans .= "Aucun match pour l'équipe séléctionnée !";
			$ans .= "</span></div>";
			return $ans;
		}
		
		$header = "<div align=\"center\"> <table class=\"resultset\">";
		$header .= "<tr> <th> Date </th> <th> Adversaire </th> ";
		$header .= "<th> Score Club</th> <th> Score Adv. </th> </tr>";
	
		$footer = "</table> </div>";
		
		return $header . $content . $footer;
	}
	
	/** Fin de l'interface de recherche **/
	
	
	
	/** Interface d'affichage HTML **/
	public function displayLong() {
		$ans = $this->displayShort();
		
		$players = "";
		$p = $this->_players;
		$tmpArray = array();
		foreach($p as $k => $v) {
			$aMember = Member::read($k);
			$licence = $aMember->getLicenceNo();
			$name = $aMember->displayName();
			$role = self::$ROLES[$v["role"]];
			$mark = self::$EXISTANT_MARK[$v["mark"]];
			$gameTime = $v["gameTime"];
			
			$table = <<<EOS
<tr>
	<td> <code> $licence </code> </td> <td> $name </td> 
	<td> $role </td> <td> $mark </td> <td> $gameTime </td>
</tr>
EOS;
			$tmpArray[$name] = $table;
		}
		ksort($tmpArray);
		foreach($tmpArray as $k => $v)
			$players .= $v;
		
		$playersText = "<h2> Notation des joueurs </h2>";
		if ($players == "")
			$playersText = "";
		else {
			$playersText .= <<<EOS
<div align="center">
<table class="resultset">
<tr> <th> Licence </th> <th> Nom </th> <th> Poste </th> 
	   <th> Notation </th> <th> Temps de Jeu </th>
</tr>
$players
</table>
</div>
EOS;
		}
		
		$goals = "";
		$g = $this->_goals;
		$tmpArray = array();
		foreach($g as $k => $v) {
			$minute = $v["minute"];
			if ($v["forUs"] == self::$FOR_US)
				$forUs = "But Mis";
			else
				$forUs = "<span class=\"error\"> But Encaissé </span>";
				
			$player = $v["player"];
			if ($player == -1)
				$player = "<span class=\"error\" >Inconnu </span>";
			else {
				$aMember = Member::read($player);
				$player = $aMember->displayName();
			}
			$helper = $v["helper"];
			if ($helper == -1)
				$helper = "<span class=\"error\" >Inconnu </span>";
			else {
				$aMember = Member::read($helper);
				$helper = $aMember->displayName();
			}
			$type = self::$GOAL_TYPE[$v["type"]];
			$loc  = self::$GOAL_LOC[$v["localisation"]];
			$comment = nl2br(PropRetriever::getProp($v,"comment"));
			if ($comment == "")
				$comment = "--";
			$table = <<<EOS
<tr>
	<th> ${minute} ' </th> 
	<th colspan="3" align="center"> ${forUs} </th>
</tr>
<tr>
	<td> <strong> Buteur </strong> </td> <td> ${player} </td>
	<td> <strong> Passeur </strong> </td> <td> ${helper} </td>
</tr>
<tr> 
	<td> <strong> Type </strong> </td> <td> ${type} </td>
	<td> <strong> Localisation </strong> </td> <td> ${loc} </td>
</tr>
<tr>
	<td> <strong> Commentaire : </strong> </td>
	<td colspan="3"> ${comment} </td>
</tr>
EOS;
			$tmpArray[$table] = $minute;
		}
		asort($tmpArray);
		foreach ($tmpArray as $k => $v)
			$goals .= $k;
			
		$goalsText = "<h2> Buts Renseignés </h2>";
		if ($goals == "")
			$goalsText = "";
		else {
			$goalsText .= <<<EOS
<div align="center">
<table class="resultset">
$goals
</table>
</div>
EOS;
		}
		
		$warnings = "";
		$w = $this->_warnings;
		$tmpArray = array();
		foreach($w as $k => $v) {
			$minute = PropRetriever::getInt($v,"minute");
			$player = PropRetriever::getProp($v,"player");
			$aMember = Member::read($player);
			$name = $aMember->displayName();
			$type = PropRetriever::getProp($v,"type");
			$type = WarningType::$WARNINGS[$type];
			$comment = nl2br(PropRetriever::getProp($v,"comment"));
			if ($comment == "")
				$comment = "--";
			$table = <<<EOS
<tr> 
	<td> ${minute}' </td> <td> ${name} </td> <td> ${type} </td> 
</tr>
<tr> 
	<td> <strong> Commentaire : </strong> </td> 
	<td colspan="2"> ${comment} </td> </tr>
EOS;
			$tmpArray[$table] = $minute;
		}
		asort($tmpArray);
		foreach ($tmpArray as $k => $v)
			$warnings .= $k;
		
		$warningsText = "<h2> Cartons Pris </h2>";
		if ($warnings == "")
			$warningsText = "";
		else {
			$warningsText .= <<<EOS
<div align="center">
<table class="resultset">
<tr> <th> Minute </th> <th> Joueur </th> <th> Type </th> </tr>
$warnings
</table>
</div>
EOS;
		}
		
		$mediaTitle = "<h2> Médias Disponibles </h2>";
		$media = "";
		
		$pictures = ""; $something = False;
		for ($i = 1; $i < 6; $i++) {
			if ($this->_pictures[$i] != "")
				$something = True;
		}
		if ($something) {
			$pic1 = $this->getPicture(1,False); $pic2 = $this->getPicture(2,False); 
			$pic3 = $this->getPicture(3,False); $pic4 = $this->getPicture(4,False); 
			$pic5 = $this->getPicture(5,False);
			$pictures = <<<EOS
<div align="center">
<table>
<tr> 
	<td align="center"> ${pic1} </td>
	<td> &nbsp; &nbsp; </td>
	<td> ${pic2} </td>
	<td> &nbsp; &nbsp; </td>
	<td> ${pic3} </td>
	<td> &nbsp; &nbsp; </td>
	<td> ${pic4} </td>
	<td> &nbsp; &nbsp; </td>
	<td> ${pic5}</td>
</tr>
</table>
</div>
EOS;
		}
		
		$picturesText = "<h3> Images </h3>";
		if ($pictures == "")
			$picturesText = "";
		else
			$picturesText .= $pictures;
		
		$movie = $this->getMovieUrl();
		$movieText = "<h3> Vidéo </h3>";
		if ($movie == "")
			$movieText = "";
		else {
			$movieText .= "<p><a href=\"".$movie."\" target=\"_blank\">";
			$movieText .= "Télécharger la vidéo </a> </p>";
		}
		
		if ($movieText != "" or $picturesText != "")
			$media = $mediaTitle . $picturesText . $movieText;
		
		$commentTitle = "<h2> Commentaires </h2>";
		$comment = "";
		
		$internal = nl2br($this->_internalComment);
		$internalText = "<h3> Interne (Accessible dans Balloon uniquement) </h3>";
		if ($internal == "")
			$internalText = "";
		else
			$internalText .= "<code> $internal </code>"; 
		
		$external = nl2br($this->_externalComment);
		$externalText = "<h3> Externe (Publié sur le Site Web) </h3> ";
		if ($external == "")
			$externalText = "";
		else
			$externalText .= "<code> $external </code>";
			
		if ($internalText != "" or $externalText != "")
			$comment = $commentTitle . $internalText . $externalText;
		
		$ans .= <<<EOS

$playersText

$goalsText

$warningsText

$media

$comment

EOS;
		return $ans;
	
	}
	
	public function displayShort() {
		
		$date = Date::fromSql($this->_date);
		//$date = $date->prettyPrint();
		$date = $date->displaySquizzed();
		
		$opponent = $this->_opponent;
		$teamName = $this->getTeamName();
		
		$matcheId = $this->_matchNo;
		if ($matcheId == "")
			$matcheId = "<code> -- </code>";
			
		$webId    = $this->_matchWebNo;
		if ($webId == "")
			$webId = "<code> -- </code>";
			
		$direction = self::$DIRECTION[$this->_direction];
		$type      = self::$MATCHE_TYPE[$this->_type];
		
		$day = $this->_day;
		if ($day == "")
			$day = "<code> -- </code>";
		
		$length = $this->_length;
		if ($length == "")
			$length = "<code> -- </code>";
		
		$us = $this->_goalsUs;
		$them = $this->_goalsThem;
		
		$ground = self::$GROUND[$this->_ground];
		$groundType = self::$GROUND_TYPE[$this->_groundType];
		
		if ($this->_ground == 2)
			$title = $opponent . " / " . $teamName;
		else
			$title = $teamName . " / " . $opponent;
			
		$page = <<<EOS
<h1> $date :  $title </h1>
<div align="center">
<table class="resultset">
  <tr>
  	<th colspan="4"> Informations Administratives </th>
  </tr>
  <tr>
  	<td> <strong> Numéro de Match </strong></td> 
  	<td> <code> $matcheId </code></td>
  	<td> <strong> Numéro Web / Minitel </strong> </td> 
  	<td> <code> $webId </code> </td>
  </tr>
  <tr>
  	<td> <strong> Sens </strong></td> 
  	<td> $direction </td>
  	<td> <strong> Type de Match </strong> </td> 
  	<td> $type </td>
  </tr>
  <tr>
  	<td> <strong> Journée </strong></td> 
  	<td> $day </td>
  	<td> <strong> Durée </strong> </td> 
  	<td> $length </td>
  </tr>
  <tr>
    <th colspan="4"> Informations Techniques </th>
  </tr>
  <tr>
  	<td> <strong> Score Club </strong></td> 
  	<td> <code> $us </code> </td>
  	<td> <strong> Score Adversaire </strong> </td> 
  	<td> <code> $them </code> </td>
  </tr>
  <tr>
  	<td> <strong> Localisation </strong> </td>
  	<td> ${ground} </td>
  	<td> <strong> Type de Terrain </strong> </td>
  	<td> ${groundType} </td>
  </tr>
</table>
</div>

EOS;
		return $page;
	}
	
	public function displayInLine($scriptUrl = "") {
		$theDate = Date::fromSQL($this->_date);
		
		$d = $theDate->prettyPrint();
		$ans = "";
		if ($scriptUrl == "") 
			$ans  .= "<td> $d </td>" ;
		else
			$ans .= "<td> <a href=\"$scriptUrl?id=".$this->_id."\"> $d </a> </td>";
			
		$ans .= "<td>" . $this->_opponent . "</td>";
		$ans .= "<td>" . $this->_goalsUs . "</td>";
		$ans .= "<td>" . $this->_goalsThem . "</td>";
		return $ans;
	}
	
	
	
	/** Fin de l'interface de visualisation **/
	
	
	public static function getTypeAsList($selected = -1) {
		$ans = "";
		asort(self::$MATCHE_TYPE);
		foreach(self::$MATCHE_TYPE as $k => $v) {
			$s = "";
			if ($k == $selected)
				$s = "selected";
			$ans .= "<option value=\"$k\" $s> $v </option>";
		}
		return $ans;
	}
	
	public static function getDirectionAsList($selected = -1) {
		$ans = "";
		foreach(self::$DIRECTION as $k => $v) {
			$s = "";
			if ($k == $selected)
				$s = "selected";
			$ans .= "<option value=\"$k\" $s> $v </option>";
		}
		return $ans;
	}
	
	/** Ponts Bajax **/
	public static function bajax_lookforMatches($params) {
		$teamId = $params[0];
		$scriptUrl = $params[1];
		
		return self::showResult(self::lookFor($teamId),$scriptUrl);
		
	}
	
	public static function getRolesAsList($roleId = -1) {
		$ans = "";
		foreach(self::$ROLES as $k => $v) {
			$s = "";
			if ($k == $roleId)
				$s = "selected";
			$ans .= "<option value=\"$k\" $s> $v </option>";
		}
		return $ans;
	}
	
	public static function getGoalTypeAsList($id = -1) {
		$ans = "";
		foreach(self::$GOAL_TYPE as $k => $v) {
			$s = "";
			if ($k == $id)
				$s = "selected";
			$ans .= "<option value=\"$k\" $s> $v </option>";
		}
		return $ans;
	}
	
	public static function getLocalisationAsList($id = -1) {
		$ans = "";
		foreach(self::$GOAL_LOC as $k => $v) {
			$s = "";
			if ($k == $id)
				$s = "selected";
			$ans .= "<option value=\"$k\" $s> $v </option>";
		}
		return $ans;
	}
	
	public static function getMarkAsList($markId = -1) {
		$ans = "";
		foreach(self::$EXISTANT_MARK as $k => $v) {
			$s = "";
			if ($k == $markId)
				$s = "selected";
			$ans .= "<option value=\"$k\" $s> $v </option>";
		}
		return $ans;
	}
	
	public function getPlayersAsList($unknown,$playerId = -1) {

		$players = array();
		foreach($this->_players as $k => $v) {
			$member = Member::read($k);
			$players[$member->displayName()] = $k;
		}
		ksort($players);

		$ans = "";
		foreach($players as $k => $v) {
			$s = "";
			if ($v == $playerId)
				$s = "selected";
			$ans .= "<option value=\"$v\" $s> $k </option>";			
		}
		if ($unknown === True)
			$ans = "<option value=\"-1\"> Inconnu </option>" . $ans;
			
		return $ans;
	}
	
	public static function getForUsAsList($id = -1) {
		$ans = "";
		if ($id == self::$FOR_US) {
			$ans = "<option value=\"".self::$FOR_US."\" selected> But Mis </option>";
			$ans .= "<option value=\"".self::$FOR_THEM."\" > But Encaissé </option>";
		}
		else {
			$ans = "<option value=\"".self::$FOR_US."\" > But Mis </option>";
			$ans .= "<option value=\"".self::$FOR_THEM."\" selected> But Encaissé </option>";
		}
		return $ans;
	}
	
	public static function getGroundAsList($id = -1) {
		$ans = "";
		foreach(self::$GROUND as $k => $v) {
			$s = "";
			if ($k == $id)
				$s = "selected";
			$ans .= "<option value=\"$k\" $s> $v </option>";
		}
		return $ans;
	}
	
	public static function getGroundTypeAsList($id = -1) {
		$ans = "";
		foreach(self::$GROUND_TYPE as $k => $v) {
			$s = "";
			if ($k == $id)
				$s = "selected";
			$ans .= "<option value=\"$k\" $s> $v </option>";
		}
		return $ans;
	}
	
}
?>